package com.heyu.cgsd.util;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.heyu.cgsd.model.bean.CurrencyBean;
import com.heyu.cgsd.model.bean.ExchangeBean;

import java.util.List;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ExchangeUtils {
    private static final String API_KEY = "622c8f754e8227b8704326837eb0cfb1";
    public static String[] titles;
    public static String[] units;
    public static float[] rates;
    private static int x = 1;

    //    http://op.juhe.cn/onebox/exchange/list?key=您申请的APPKEY
    //    http://op.juhe.cn/onebox/exchange/currency?key=您申请的APPKEY&from=JPY&to=BHD
    public static void getExchange() {
        String url = "http://op.juhe.cn/onebox/exchange/list?key=" + API_KEY;
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            String data = response.body().string();
            Gson gson = new Gson();
            ExchangeBean exchangeBean = gson.fromJson(data, ExchangeBean.class);
            List<ExchangeBean.ResultBean.ListBean> listBeans = exchangeBean.getResult().getList();
            int size = listBeans.size();

            titles = new String[size];
            units = new String[size];
            for (int i = 0; i < size; i++) {
                titles[i] = listBeans.get(i).getName();
                units[i] = listBeans.get(i).getCode();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static float getCurrency(String from, String to) {
        String url = "http://op.juhe.cn/onebox/exchange/currency?key=" + API_KEY + "&from=" + from + "&to=" + to;
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            String data = response.body().string();
            Gson gson = new Gson();
            CurrencyBean currencyBean = gson.fromJson(data, new TypeToken<CurrencyBean>() {
            }.getType());
            List<CurrencyBean.ResultBean> resultBeanList = currencyBean.getResult();
            if (resultBeanList != null) {
                String x = resultBeanList.get(0).getResult();
                return Float.valueOf(x);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0.0f;
    }
}